package org.example.aitest.utils.gen;

import org.example.aitest.dto.TableColumn;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * 代码生成工具，实现生成数据库表后直接生成entity,service和mapper
 * */
@Component
public class CodeGenerator {

    @Value("${code.generator.base-package:org.example.aitest}")
    private String basePackage;

    @Value("${code.generator.output-dir:src/main/java}")
    private String outputDir;

    /**
     * 生成 Entity、Mapper、Service
     */
    public void generateCode(String tableName, List<TableColumn> columns,Integer upController) {
        String className = toCamelCase(tableName, true); // 表名转大驼峰（如 user_info → UserInfo）
        String varName = toCamelCase(tableName, false); // 变量名（小驼峰，如 userInfo）

        // 生成 Entity
        generateEntity(className, columns);
        
        // 生成 Mapper
        generateMapper(className,columns,tableName);

        // 生成 Service
        generateServiceInterface(className);
        // 生成 ServiceImpl
        generateService(className, varName);

        if(upController == 1) {
            // 更新controller
            updateCreateTableController(className, varName, tableName);
        } else if (upController == 2) {
            //第二种更新方法
            updateDownloadMethod(className, varName);
        }
    }

    /**
     * 生成 Entity 类
     */
    private void generateEntity(String className, List<TableColumn> columns) {
        String entityPackage = basePackage + ".entity";
        //处理名称
        String name = PinyinUtils.sanitizeTableName(className);
        String filePath = outputDir + "/" + entityPackage.replace(".", "/") + "/" + name + ".java";

        String content = buildEntityCode(name, columns); // 提取生成代码的逻辑
        generateFile(filePath, content);
    }

    private String buildEntityCode(String className, List<TableColumn> columns) {
        StringBuilder code = new StringBuilder();
        code.append("package ").append(basePackage).append(".entity;\n\n");
        code.append("import lombok.Data;\n");
        code.append("import javax.persistence.*;\n");
        code.append("import java.math.BigDecimal;\n");
        code.append("import java.util.*;\n\n");
        code.append("@Data\n");
        code.append("@Entity\n");
        code.append("@Table(name = \"").append(className).append("\")\n");
        code.append("public class ").append(className).append(" {\n\n");
        code.append("    @Id\n");
        code.append("    @GeneratedValue(strategy = GenerationType.IDENTITY)\n");
        code.append("    private Long id;\n\n");

        // 生成字段
        for (TableColumn column : columns) {
            // 处理字段名
            String name = PinyinUtils.sanitizeTableName(column.getName());
            String cname = PinyinUtils.sanitizeTableName(name);
            String fieldType = getJavaType(column.getType());
            String fieldName = toCamelCase(cname, false);
            code.append("    @Column(name = \"").append(cname).append("\")\n");
            code.append("    private ").append(fieldType).append(" ").append(fieldName).append(";\n\n");
        }
        code.append("    private Date createTime;\n");
        code.append("    private Date updateTime;\n");

        code.append("   public Map<String,Class<?>> getMapType(){\n");
        code.append("       Map<String,Class<?>> map = new HashMap<>();\n");
        for (TableColumn column : columns) {
            // 处理字段名
            String name = PinyinUtils.sanitizeTableName(column.getName());
            String cname = PinyinUtils.sanitizeTableName(name);
            String fieldType = getJavaType(column.getType());
            code.append("       map.put(\""+cname+"\","+fieldType+".class);\n");
        }
        code.append("       return map;\n");
        code.append("   }\n\n");

        code.append("   public Map<String,Object> getMap(){\n");
        code.append("       Map<String,Object> map = new HashMap<>();\n");
        for (TableColumn column : columns) {
            // 处理字段名
            String name = PinyinUtils.sanitizeTableName(column.getName());
            String cname = PinyinUtils.sanitizeTableName(name);
            String s = toCamelCase(cname, true);
            code.append("       map.put(\""+cname+"\",this.get"+s+"());\n");
        }
        code.append("       return map;\n");
        code.append("   }\n");
        code.append("\n");

        code.append("   public List<Object> getAllGet(){\n");
        code.append("       List<Object> list = new ArrayList<>();\n");
        for (TableColumn column : columns) {
            // 处理字段名
            String name = PinyinUtils.sanitizeTableName(column.getName());
            String cname = PinyinUtils.sanitizeTableName(name);
            String s = toCamelCase(cname, true);
            code.append("       list.add(this.get"+s+"());\n");
        }
        code.append("       return list;\n");
        code.append("   }\n");

        code.append("}\n");
        return code.toString();
    }

    /**
     * 生成 Mapper 接口
     */
    private void generateMapper(String className,List<TableColumn> columns,String tableName) {
        String mapperPackage = basePackage + ".mapper";
        String name = PinyinUtils.sanitizeTableName(className);
        String filePath = outputDir + "/" + mapperPackage.replace(".", "/") + "/" + name + "Mapper.java";

        //生成mapper接口文件
        String content = buildMapperCode(name);
        generateFile(filePath, content);

        //生成xml映射文件
        String resourcesDir = outputDir.replace("src/main/java", "src/main/resources/");
        String xmlFilePath = resourcesDir + mapperPackage.replace(".", "/") + "/" + name + "Mapper.xml";
        String xmlContent = buildMapperXml(name, columns, tableName);
        generateFile(xmlFilePath, xmlContent);
    }

    private String buildMapperCode(String className) {
        String format = String.format("""
                        package %s.mapper;
                                
                        import %s.entity.%s;
                        import org.apache.ibatis.annotations.Select;
                        import com.baomidou.mybatisplus.core.mapper.BaseMapper;
                        import org.apache.ibatis.annotations.Mapper;
                                
                        import java.util.List;
                        import java.util.Map;
                        @Mapper
                        public interface %sMapper extends BaseMapper<%s> {
                            // 自定义查询方法
                                
                            /**
                             * 获取表的完整列信息
                             * @param tableName 表名
                             * @return 包含列名、注释、类型、长度等信息的Map列表
                             */
                            @Select("SELECT " +
                                    "COLUMN_NAME AS columnName, " +
                                    "COLUMN_COMMENT AS columnComment, " +
                                    "COLUMN_TYPE AS columnType, " +
                                    "DATA_TYPE AS dataType, " +
                                    "CHARACTER_MAXIMUM_LENGTH AS maxLength, " +
                                    "NUMERIC_PRECISION AS numericPrecision, " +
                                    "NUMERIC_SCALE AS numericScale, " +
                                    "IS_NULLABLE AS nullable, " +
                                    "COLUMN_KEY AS columnKey, " +
                                    "EXTRA AS extra " +
                                    "FROM information_schema.COLUMNS " +
                                    "WHERE TABLE_SCHEMA = (SELECT DATABASE()) AND TABLE_NAME = #{tableName} " +
                                    "ORDER BY ORDINAL_POSITION")
                            List<Map<String, Object>> getColumnComments(String tableName);
                            
                            //查询数据方法
                            %s getData(%s %s);
                        }
                        """,
                basePackage,
                basePackage, className,
                className, className,
                className,className,className.toLowerCase());
        return format;
    }

    private String buildMapperXml(String className, List<TableColumn> columns, String tableName) {
        StringBuilder xml = new StringBuilder();
        String lowerClassName = className.toLowerCase();

        // XML文件头
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
        xml.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
        xml.append(String.format("<mapper namespace=\"%s.mapper.%sMapper\">\n", basePackage, className));

        // 定义结果映射  toCamelCase转驼峰命名，false为转小驼峰
        xml.append("    <resultMap id=\"BaseResultMap\" type=\"").append(basePackage).append(".entity.").append(className).append("\">\n");
        for (TableColumn column : columns) {
            String propertyName = PinyinUtils.sanitizeTableName(column.getName());
            xml.append("        <result column=\"").append(column.getName())
                    .append("\" property=\"").append(toCamelCase(propertyName,false)).append("\"/>\n");
        }
        xml.append("    </resultMap>\n\n");

        // 查询SQL定义
        xml.append("    <select id=\"getData\" resultMap=\"BaseResultMap\">\n");
        xml.append("        SELECT ");

        // 添加查询字段
        for (int i = 0; i < columns.size(); i++) {
            if (i > 0) {
                xml.append(", ");
            }
            xml.append(columns.get(i).getName());
        }

        // 添加表名和条件
        xml.append("\n        FROM ").append(tableName).append("\n");
        xml.append("        <where>\n");

        // 动态条件
        for (TableColumn column : columns) {
            String propertyName = PinyinUtils.sanitizeTableName(column.getName());
            xml.append("            <if test=\"").append(toCamelCase(propertyName,false)).append(" != null\">\n");
            xml.append("                AND ").append(column.getName())
                    .append(" = #{").append(toCamelCase(propertyName,false)).append("}\n");
            xml.append("            </if>\n");
        }

        xml.append("        </where>\n");
        xml.append("    </select>\n");
        xml.append("</mapper>");

        return xml.toString();
    }

    /**
     * 生成service接口
     * */
    private void generateServiceInterface(String className) {
        String packageName = basePackage + ".service";
        String name = PinyinUtils.sanitizeTableName(className);
        String filePath = outputDir + "/" + packageName.replace(".", "/") + "/" + name + "Service.java";
        String content = buildServiceInterfaceCode(name);
        generateFile(filePath, content);
    }

    private String buildServiceInterfaceCode(String className) {
        return String.format("""
        package %s.service;
        
        import %s.entity.%s;
        import com.baomidou.mybatisplus.extension.service.IService;
        
        import java.util.List;
        import java.util.Map;

        public interface %sService extends IService<%s> {
            // 自定义扩展方法
            List<%s> getAll();

            List<Map<String, Object>> getColumnComments(String tableName);
            
            %s getData(%s %s);
        }
        """,
                basePackage,
                basePackage, className,
                className, className,
                className,
                className,className,className.toLowerCase());
    }

    /**
     * 生成 Service 层
     */
    private void generateService(String className, String varName) {
        String servicePackage = basePackage + ".service.impl";
        String name = PinyinUtils.sanitizeTableName(className);
        String filePath = outputDir + "/" + servicePackage.replace(".", "/") + "/" + name + "ServiceImpl.java";
        String content = buildServiceImplCode(name, varName);

        generateFile(filePath, content);
    }

    private String buildServiceImplCode(String className, String varName) {
        return String.format("""
                        package %s.service.impl;
                                
                        import %s.entity.%s;
                        import %s.mapper.%sMapper;
                        import %s.service.%sService;
                        import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
                        import org.springframework.beans.factory.annotation.Autowired;
                        import org.springframework.stereotype.Service;
                                
                        import java.util.List;
                        import java.util.Map;

                        @Service("%sService")
                        public class %sServiceImpl extends ServiceImpl<%sMapper, %s> implements %sService {
                            // 自定义业务方法
                            @Autowired
                            private %sMapper mapper;

                            @Override
                            public List<%s> getAll(){
                                return mapper.selectList(null);
                            }

                            @Override
                            public List<Map<String, Object>> getColumnComments(String tableName){
                                return mapper.getColumnComments(tableName);
                            }
                            
                            @Override
                            public %s getData(%s %s){
                                 return mapper.getData(%s);
                            }
                        }
                        """,
                basePackage,
                basePackage, className,
                basePackage, className,
                basePackage, className,
                className,
                className, className, className, className,
                className,
                className,
                className,className,className.toLowerCase(),
                className.toLowerCase());
    }

    /**
     * 数据库类型 → Java 类型
     */
    private String getJavaType(String dbType) {
        return switch (dbType.toUpperCase()) {
            case "VARCHAR", "TEXT" -> "String";
            case "INT", "BIGINT" -> "Long";
            case "DECIMAL" -> "BigDecimal";
            case "DATETIME", "TIMESTAMP" -> "Date";
            case "BOOLEAN" -> "Boolean";
            default -> "Object";
        };
    }

    /**
     * 下划线命名 → 驼峰命名
     * @param str 原始字符串
     * @param isBigCamel 是否大驼峰（如 UserInfo）
     * @return 转换后的字符串
     */
    private String toCamelCase(String str, boolean isBigCamel) {
        String[] parts = str.split("_");
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < parts.length; i++) {
            String part = parts[i];

            // 跳过空部分（连续下划线情况）
            if (part.isEmpty()) {
                continue;
            }

            // 处理数字情况：如果下一部分是数字，则保持原样
            if (i < parts.length - 1 && isNumeric(parts[i + 1])) {
                if (i == 0 && !isBigCamel) {
                    result.append(part.toLowerCase());
                } else {
                    result.append(part.substring(0, 1).toUpperCase())
                            .append(part.substring(1).toLowerCase());
                }
                result.append("_").append(parts[i + 1]); // 添加下划线和数字部分
                i++; // 跳过已处理的数字部分
                continue;
            }

            // 常规处理
            if (i == 0 && !isBigCamel) {
                result.append(part.toLowerCase());
            } else {
                result.append(part.substring(0, 1).toUpperCase())
                        .append(part.substring(1).toLowerCase());
            }
        }

        return result.toString();
    }

    /**
     * 判断字符串是否为数字
     */
    private boolean isNumeric(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }

    private void generateFile(String filePath, String content) {
        File file = new File(filePath);
        File parentDir = file.getParentFile();

        // 如果父目录不存在，则创建
        if (!parentDir.exists()) {
            parentDir.mkdirs(); // 递归创建目录
        }

        try (FileWriter writer = new FileWriter(file)) {
            writer.write(content);
        } catch (IOException e) {
            throw new RuntimeException("生成文件失败: " + filePath, e);
        }
    }

    private void updateCreateTableController(String className, String varName, String tableName) {
        String controllerPackage = basePackage + ".controller";
        String filePath = outputDir + "/" + controllerPackage.replace(".", "/") + "/CreateTableController.java";

        try {
            // 1. 如果文件不存在，则创建
            if (!Files.exists(Paths.get(filePath))) {
                createNewCreateTableController(filePath, controllerPackage);
                return;
            }

            String content = new String(Files.readAllBytes(Paths.get(filePath)));

            // 2. 添加服务导入
            String serviceImport = "import " + basePackage + ".service." + className + "Service;\n" +
                    "import "+ basePackage + ".service.impl."+className+"ServiceImpl;";
            if (!content.contains(serviceImport)) {
                content = addImport(content, serviceImport);
            }

            // 3. 添加实体类导入
            String entityImport = "import " + basePackage + ".entity." + className + ";";
            if (!content.contains(entityImport)) {
                content = addImport(content, entityImport);
            }

            // 4. 添加服务注入
            String serviceField = "\n    @Autowired\n" +
                    "    private " + className + "Service " + varName + "Service;\n";
            if (!content.contains("private " + className + "Service " + varName + "Service;")) {
                int classBodyStart = content.indexOf("{") + 1;
                content = content.substring(0, classBodyStart) + serviceField + content.substring(classBodyStart);
            }

            // 5. 添加服务调用代码块
            String tableVarName = className.toLowerCase() + "Table";
            String mapVarName = className.toLowerCase() + "Maps";
            String serviceCall = "\n        List<" + className + "> " + className.toLowerCase() + " = " + varName + "Service.getAll();\n" +
                    "        List<Map<String,Object>> " + tableName + "List = " + varName +
                    "Service.getColumnComments(\"" + tableName + "\");\n" +
                    "        List<TableColumn> " + tableVarName + " = excelComp.createTable(file," + tableName + "List," + className + ".class," + className + "Service.class);\n" +
                    "        List<Map<String, Object>> " + mapVarName + " = excelComp.insertData(file," + className + ".class," + className + "Service.class);";

            if (!content.contains(varName + "Service.getAll()")) {
                int compareMethodStart = content.indexOf("@PostMapping(\"/compare\")");
                if (compareMethodStart != -1) {
                    int methodBodyStart = content.indexOf("{", compareMethodStart) + 1;
                    content = content.substring(0, methodBodyStart) + serviceCall + content.substring(methodBodyStart);
                }
            }

            // 6. 更新两个Stream.concat调用
            content = updateStreamConcat(content, "List<TableColumn> list = Stream.concat(", tableVarName + ".stream()");
            content = updateStreamConcat(content, "List<Map<String, Object>> list1 = Stream.concat(", mapVarName + ".stream()");

            // 7. 保存修改
            try (FileWriter writer = new FileWriter(filePath)) {
                writer.write(content);
            }
        } catch (IOException e) {
            throw new RuntimeException("更新 CreateTableController 失败", e);
        }
    }

    // 辅助方法：添加import语句
    private String addImport(String content, String importStatement) {
        int lastImportIndex = content.lastIndexOf("import ");
        if (lastImportIndex != -1) {
            lastImportIndex = content.indexOf("\n", lastImportIndex) + 1;
            return content.substring(0, lastImportIndex) + importStatement + "\n" + content.substring(lastImportIndex);
        } else {
            int packageEnd = content.indexOf(";") + 1;
            return content.substring(0, packageEnd) + "\n" + importStatement + content.substring(packageEnd);
        }
    }

    // 辅助方法：更新Stream.concat调用
    private String updateStreamConcat(String content, String concatStartMarker, String streamToAdd) {
        int concatStartIndex = content.indexOf(concatStartMarker);

        if (concatStartIndex != -1) {
            int concatEndIndex = content.indexOf(").distinct().collect(Collectors.toList());", concatStartIndex);
            String existingConcat = content.substring(concatStartIndex + concatStartMarker.length(), concatEndIndex);

            // 检查是否已经包含当前stream
            if (!existingConcat.contains(streamToAdd)) {
                String newConcat;
                if (existingConcat.isEmpty()) {
                    // 如果concat是空的，直接添加
                    newConcat = streamToAdd;
                } else {
                    // 如果已经有内容，用逗号分隔添加
                    newConcat = existingConcat + ", " + streamToAdd;
                }

                // 替换原有内容
                content = content.substring(0, concatStartIndex + concatStartMarker.length()) +
                        newConcat +
                        content.substring(concatEndIndex);
            }
        } else {
            // 如果没有找到对应的Stream.concat，创建新的
            String newStreamCode = "\n        " + concatStartMarker + streamToAdd + ").distinct().collect(Collectors.toList());";
            int redisIndex = content.indexOf("redisTemplate.opsForValue().set(\"new_bak_table_name\",s);");
            if (redisIndex != -1) {
                int insertPos = content.indexOf("\n", redisIndex) + 1;
                content = content.substring(0, insertPos) + newStreamCode + content.substring(insertPos);
            }
        }

        return content;
    }

    /**
     * 创建新的 CreateTableController
     */
    private void createNewCreateTableController(String filePath, String controllerPackage) throws IOException {
        // 确保目录存在
        new File(filePath).getParentFile().mkdirs();

        // 创建文件并写入基础内容
        try (FileWriter writer = new FileWriter(filePath)) {
            String baseContent = "package " + controllerPackage + ";\n\n" +
                    "import org.apache.poi.xssf.usermodel.XSSFWorkbook;\n" +
                    "import org.example.aitest.dto.TableColumn;\n" +
                    "import com.alibaba.fastjson2.JSONArray;\n" +
                    "import com.alibaba.fastjson2.JSONObject;\n" +
                    "import org.example.aitest.utils.gen.*;\n" +
                    "import org.springframework.beans.factory.annotation.Autowired;\n" +
                    "import org.springframework.data.redis.core.RedisTemplate;\n" +
                    "import org.springframework.web.bind.annotation.*;\n" +
                    "import org.springframework.web.multipart.MultipartFile;\n" +
                    "\n" +
                    "import java.util.*;\n" +
                    "import java.io.OutputStream;\n" +
                    "import java.util.stream.Collectors;" +
                    "import java.util.stream.Stream;\n" +
                    "\n" +
                    "import javax.servlet.http.HttpServletResponse;" +
                    "\n\n" +
                    "@RestController\n" +
                    "@RequestMapping(\"/create\")\n" +
                    "public class CreateTableController {\n\n" +
                    "    @Autowired\n" +
                    "    private ExcelComp excelComp;\n" +
                    "    @Autowired\n" +
                    "    private RedisTemplate redisTemplate;\n" +
                    "    @Autowired\n" +
                    "    public DynamicTableGenerator dynamicTableGenerator;\n" +
                    "    @Autowired\n" +
                    "    public DynamicDataService dataService;\n" +
                    "    /**\n" +
                    "     * 比较搜索内容，以传入表的某一列为基础,以备注名相同时匹配内容\n" +
                    "     * 即使都不同，但是匹配上都写入，依次往后填\n" +
                    "     */\n" +
                    "    @PostMapping(\"/compare\")\n" +
                    "    public void compare(@RequestParam MultipartFile file) throws Exception {\n" +
                    "        //下面四行创建后就不变\n" +
                    "        String name = file.getOriginalFilename();\n" +
                    "        String firstLetters = PinyinUtils.getFirstLetters(name);\n" +
                    "        String s = PinyinUtils.sanitizeTableName(firstLetters);\n" +
                    "        redisTemplate.opsForValue().set(\"new_bak_table_name\",s+\"_bak\");\n\n" +
                    "        //每更新一次就往concat中添加一个list.stream()\n" +
                    "        //List<TableColumn> list = Stream.concat().distinct().collect(Collectors.toList());\n" +
                    "        //List<Map<String, Object>> list1 = Stream.concat().distinct().collect(Collectors.toList());" +
                    "        //创建数据库表\n" +
                    "        dynamicTableGenerator.createTable(s +\"_bak\",list,name,2);\n" +
                    "        \n" +
                    "        //往表中添加数据\n" +
                    "        for (Map<String, Object> objectMap : list1) {\n" +
                    "            dataService.insertData(s+\"_bak\",objectMap);\n" +
                    "        }\n" +
                    "       \n" +
                    "    }\n\n" +
                    "    // 将生成的新表数据以excel文件格式输出\n" +
                    "    @GetMapping(\"/download\")\n" +
                    "    public void download(HttpServletResponse response) throws Exception {\n" +
                    "        String tableName = (String) redisTemplate.opsForValue().get(\"new_bak_table_name\");\n" +
                    "        XSSFWorkbook excel = new XSSFWorkbook();\n" +
                    "        //使用输出流进行表格下载,基于浏览器下载\n" +
                    "        OutputStream out = response.getOutputStream();\n" +
                    "        response.setContentType(\"application/vnd.ms-excel\");  //代表excel文件\n" +
                    "        response.setHeader(\"content-Disposition\", \"attachment;filename=me.xlsx\"); //文件下载类型，以附件形式进行下载\n" +
                    "        excel.write(out);\n" +
                    "        out.flush();\n" +
                    "        out.close();\n" +
                    "        excel.close();\n" +
                    "    }\n" +
                    "}\n";

            writer.write(baseContent);
        }
    }

    private void updateDownloadMethod(String className, String varName) {
        String controllerPackage = basePackage + ".controller";
        String filePath = outputDir + "/" + controllerPackage.replace(".", "/") + "/CreateTableController.java";

        try {
            // 确保文件存在
            if (!Files.exists(Paths.get(filePath))) {
                createNewCreateTableController(filePath, controllerPackage);
                return;
            }

            String content = new String(Files.readAllBytes(Paths.get(filePath)));

            // 1. 添加必要的import语句
            String[] requiredImports = {
                    "import " + basePackage + ".service." + className + "Service;",
                    "import " + basePackage + ".entity." + className + ";",
                    "import org.springframework.data.redis.core.RedisTemplate;",
                    "import com.alibaba.fastjson2.JSONArray;",
                    "import com.alibaba.fastjson2.JSONObject;"
            };

            for (String imp : requiredImports) {
                if (!content.contains(imp.split(" ")[1])) {  // 检查import的基本部分
                    int lastImportIndex = content.lastIndexOf("import ");
                    if (lastImportIndex != -1) {
                        lastImportIndex = content.indexOf("\n", lastImportIndex) + 1;
                        content = content.substring(0, lastImportIndex) + imp + "\n" + content.substring(lastImportIndex);
                    } else {
                        int packageEnd = content.indexOf(";") + 1;
                        content = content.substring(0, packageEnd) + "\n" + imp + content.substring(packageEnd);
                    }
                }
            }

            // 2. 添加服务注入和RedisTemplate注入
            String serviceField = "    @Autowired\n" +
                    "    private " + className + "Service " + varName + "Service;\n";

            // 检查是否已存在RedisTemplate注入
            boolean hasRedisTemplate = content.contains("private RedisTemplate redisTemplate;");

            // 在适当位置插入服务注入
            if (!content.contains("private " + className + "Service " + varName + "Service;")) {
                if (hasRedisTemplate) {
                    // 如果已有RedisTemplate，插入在其后
                    int redisTemplateIndex = content.indexOf("private RedisTemplate redisTemplate;");
                    int insertPosition = content.indexOf("\n", redisTemplateIndex) + 1;
                    content = content.substring(0, insertPosition) + serviceField + content.substring(insertPosition);
                } else {
                    // 否则插入在最后一个@Autowired字段后
                    int lastAutowiredIndex = content.lastIndexOf("@Autowired");
                    if (lastAutowiredIndex != -1) {
                        int fieldEndIndex = content.indexOf(";", lastAutowiredIndex) + 1;
                        content = content.substring(0, fieldEndIndex) + "\n" + serviceField + content.substring(fieldEndIndex);
                    } else {
                        // 如果没有@Autowired字段，插入在类体开始处
                        int classBodyStart = content.indexOf("{") + 1;
                        content = content.substring(0, classBodyStart) + serviceField + content.substring(classBodyStart);
                    }
                }
            }

            // 3. 更新download方法 - 关键修改部分
            String serviceCall = "\n        List<" + className + "> " + varName + "ServiceAll = " + varName + "Service.getAll();\n" +
                    "        List<Map<String, Object>> " + varName + "ServiceCm = " + varName + "Service.getColumnComments(tableName);\n" +
                    "        excelComp.addTableToExcel(" + varName + "ServiceCm, excel, " + varName + "ServiceAll);\n";

            int downloadMethodStart = content.indexOf("@GetMapping(\"/download\")");
            if (downloadMethodStart != -1) {
                int workbookLineIndex = content.indexOf("XSSFWorkbook excel = new XSSFWorkbook();", downloadMethodStart);

                if (workbookLineIndex != -1) {
                    int insertPosition = content.indexOf("\n", workbookLineIndex) + 1;

                    // 检查是否已经包含该服务调用
                    if (!content.substring(downloadMethodStart).contains(varName + "Service.getAll()")) {
                        // 在XSSFWorkbook创建后插入服务调用代码
                        content = content.substring(0, insertPosition) + serviceCall + content.substring(insertPosition);
                    }
                }
            }

            // 4. 删除可能存在的旧for循环代码
            int forLoopStart = content.indexOf("for (int i = 0; i < tableNames.size(); i++)");
            if (forLoopStart != -1) {
                int forLoopEnd = findMatchingClosingBrace(content, forLoopStart);
                content = content.substring(0, forLoopStart) + content.substring(forLoopEnd + 1);
            }

            // 保存修改
            try (FileWriter writer = new FileWriter(filePath)) {
                writer.write(content);
            }
        } catch (IOException e) {
            throw new RuntimeException("更新 CreateTableController 的 download 方法失败", e);
        }
    }

    // 辅助方法：找到匹配的闭合大括号
    private int findMatchingClosingBrace(String content, int startIndex) {
        int openBraces = 1;
        int index = startIndex + 1;

        while (index < content.length() && openBraces > 0) {
            char c = content.charAt(index);
            if (c == '{') {
                openBraces++;
            } else if (c == '}') {
                openBraces--;
            }
            index++;
        }

        return index - 1;
    }

    // 转换为实体类名格式（如 cgjg_14_xlsx_0 → Cgjg_14Xlsx_0）
    private String toEntityClassName(String originalName) {
        String[] parts = originalName.split("_");
        StringBuilder result = new StringBuilder();
        for (String part : parts) {
            if (!part.isEmpty()) {
                result.append(part.substring(0, 1).toUpperCase())
                        .append(part.substring(1).toLowerCase());
            }
        }
        return result.toString();
    }
}